<?php

namespace app\store\controller\finance;

use app\store\controller\Controller;
use app\store\model\User as UserModel;
use app\common\model\GetTui as GetTuiModel;
use app\store\model\Setting as SettingModel;

/**
 * 用户充值
 * Class User
 * @package app\store\controller
 */
class User extends Controller
{
    /**
     * 用户充值
     * @return mixed
     * @throws \think\exception\DbException
     */
    public function index()
    {
		$where = [];
		$string = $this->request->param('string/s' , '');
      	$wherenew = '';
		if( $string ) {
			$wherenew = "`mobile` = '{$string}' OR `nickname` = '{$string}' OR `cart_sn` = '{$string}'";
		}
		$datetime = $this->request->param('datetime/s' ,'');
		if( $datetime ) {
			$datetime = explode(" ~ " , $datetime);
			$where['open_cart_time'] = [['egt' , strtotime($datetime[0])],['elt' , strtotime($datetime[1]) + 24 * 3600 - 1]];
			//print_r( $where );die;
		}
		$is_cart = $this->request->param('is_cart/d' , 0);
		if( $is_cart > 0 ) {
			$where['is_open_cart'] = $is_cart - 1;
		}
        $model = new UserModel;
        $list = $model->getList( $where , $wherenew );
		if( $list ) {
			foreach( $list as $k => $v ) {
				$list[$k]['parent_nickname'] = '无';
             	$list[$k]['parent_mobile'] = '--';
				if( $v['parent_id'] > 0 ) {
					$list[$k]['parent_nickname'] = db("user")->where(['user_id' => $v['parent_id']])->value("nickname");
					$list[$k]['parent_mobile'] = db("user")->where(['user_id' => $v['parent_id']])->value("mobile");
				}
			}
		}
        return $this->fetch('index', compact('list'));
    }
    
    public function recharge() {
        $id = $this->request->param('id/d' , 0);
        $num = $this->request->param('num/d' , 0);
        $type = $this->request->param('type/d' , 0);
        $note = $this->request->param('note');
        if( $id <= 0 ) $this->error('参数错误，请核对');
        $model = new UserModel;
        $info = $model->where(['user_id' => $id])->find();
        if( !$info ) $this->error('数据不存在，请核对');
        if( $type == 1 ) { //余额充值
            $field = 'money';
            $content = '通过后台充值余额：' . $num . '元';
        } else { //积分充值
            $field = 'integral';
            $content = '通过后台充值积分：' . $num . '分';
        }
        $result = $model->where(['user_id' => $id])->update([$field => $info[$field] + $num , 'total_' . $field => $info['total_' . $field] + $num]);
        if( $result ) {
            //写入日志
            db("user_".$field."_log")->insert([
                'user_id' => $id,
                'num' => $num,
                'content' => $content . ( $note == '' ? '' : '，备注：' .$note ) ,
                'type' => $num >= 0 ? 1 : 2,
                'create_time' => time()
            ]);
			$obj = new  GetTuiModel;
			$obj->sendToClient($info['user_id'] , '充值消息提示' , '平台已为您充值【'.$num.'】'.($type == 1?'元':'积分').',详情请在个人中心查看');
            $this->success('充值成功');
        } else {
            $this->error("充值失败，请重试");
        }
    }
	
	public function opencart() {
		$user_id = $this->request->param("user_id/d" , 0);
		if( $user_id <= 0 ) $this->error("数据异常");
		$user_info = db("user")->where(['user_id' => $user_id])->find();
		if( !$user_info ) $this->error("数据异常");
		
		$data = SettingModel::getItem('distribution');
		if( isset( $data['order_price'] ) && $data['order_price'] > 0 ) {
			$info = [
				'ordersn' => date("YmdHis") . rand(1000 , 9999),
				'user_id' => $user_id,
				'price' => $data['order_price'],
				'service_num' => $data['order_consumption_num'],
				'pay_type' => 4,
				'pay_time' => time(),
				'transaction_id' => date("YmdHis") . rand(100000 , 999999),
				'restart' => $user_info['is_open_cart'],
				'status' => 1,
				'create_time' => time()
			];
			$result = db("member_cart_order")->insert( $info );
			$order_id = db("member_cart_order")->getLastInsID();
			if( $result ) {
				//推荐奖励
				$usermodel = new UserModel;
				$usermodel->builddistribution( $info['ordersn'] );
				//团队奖励
				//$usermodel->colonelReward($user_id , $order_id);
				$obj = new  GetTuiModel;
				$obj->sendToClient($user_id , ( $user_info['is_open_cart'] == 1 ? '会员卡续卡成功' : '会员卡开通成功' ) , ( $user_info['is_open_cart'] == 1 ? '平台已为您续卡，详情请在个人中心查看' : '平台已为您开通会员卡，详情请在个人中心查看' ) );
				$this->success("会员开通成功");
			} else {
				$this->error("开通失败");
			}
		} else {
			$this->error("请联系管理员，错误码：30001");
		}
	}
}
